from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)

# 设置上传文件的目录
UPLOAD_FOLDER = 'uploads/'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 确保文件名是安全的
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in {'mp3'}

@app.route('/upload_mp3/<task_id>', methods=['POST'])
def upload_mp3(task_id):
    # 检查是否有文件被上传
    if 'file' not in request.files:
        return jsonify({'message': '没有训练数据文件'}), 400
    file = request.files['file']
    # 如果用户没有选择文件，浏览器也会提交一个无文件的文件对象
    if file.filename == '':
        return jsonify({'message': 'No selected file'}), 400
    if file and allowed_file(file.filename):
        # 保存文件到指定目录
        #filename = secure_filename(file.filename)
        filename = file.filename
        print('filename',filename,file.filename)
        file.save(os.path.join(UPLOAD_FOLDER, task_id+filename))
        return jsonify({'message': f'File uploaded successfully', 'filename': filename}), 200
    else:
        return jsonify({'message': 'File type not allowed'}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)